/*
 * Powered By XY
 * Since 2020
 */

package com.xy.biz.ts.service.impl;

import com.xy.biz.fd.client.DocumentClient;
import com.xy.biz.fd.domain.req.document.GetDocumentRequest;
import com.xy.biz.fd.domain.resp.GetDocumentResponse;
import com.xy.biz.ts.domain.bo.ExaminationRecordBO;
import com.xy.biz.ts.domain.bo.LearnRecordBO;
import com.xy.biz.ts.domain.bo.TrainBO;
import com.xy.biz.ts.domain.converter.ExaminationRecordConverter;
import com.xy.biz.ts.domain.converter.LearnRecordConverter;
import com.xy.biz.ts.domain.query.LearnRecordQuery;
import com.xy.biz.ts.domain.query.TrainQuery;
import com.xy.biz.ts.domain.resp.GetExaminationRecordResponse;
import com.xy.biz.ts.domain.resp.GetLearnRecordResponse;
import com.xy.biz.ts.manager.LearnRecordManager;
import com.xy.biz.ts.manager.TrainManager;
import com.xy.biz.ts.service.LearnRecordService;
import com.xy.biz.uc.client.UserClient;
import com.xy.biz.uc.domain.constant.RoleConstant;
import com.xy.biz.uc.domain.dto.UserDTO;
import com.xy.biz.uc.domain.req.GetUserRequest;
import com.xy.lang.domain.LongIdCodeName;
import com.xy.lang.domain.Result;
import com.xy.lang.util.ResultUtils;
import com.xy.tool.context.UserContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 *
 *
 * @author yzh
 * @date 2021-3-29
 */
@Service
public class LearnRecordServiceImpl implements LearnRecordService {

    @Autowired
    private LearnRecordManager learnRecordManager;
    @Autowired
    private UserClient userClient;
    @Autowired
    private DocumentClient documentClient;
    @Autowired
    private TrainManager trainManager;

    @Override
    public Result<?> saveLearnRecord(LearnRecordBO learnRecordBO) {
        buildLearnRecordBO(learnRecordBO);
        int affectedRows = learnRecordManager.saveLearnRecord(learnRecordBO);
        if (affectedRows > 0) {
            return Result.success();
        }
        return Result.ofErrorRowsAffected();
    }

    private void buildLearnRecordBO(LearnRecordBO learnRecordBO) {
        if (StringUtils.isEmpty(learnRecordBO.getLessonName())) {
            GetDocumentResponse document = ResultUtils.get(documentClient.getDocument(
                    GetDocumentRequest.builder().documentId(learnRecordBO.getLessonId()).build()));
            Objects.requireNonNull(document);
            learnRecordBO.setLessonName(document.getDocumentName());
        }
        learnRecordBO.setLessonDuration(0);
        learnRecordBO.setLearnUserId(UserContextHolder.getUserId());
        learnRecordBO.setLearnUserName(UserContextHolder.getUserName());
        learnRecordBO.setLessonType(1);
        learnRecordBO.setTenantId(UserContextHolder.getTenantId());
        learnRecordBO.setCreateUserId(UserContextHolder.getUserId());
        learnRecordBO.setCreateTime(LocalDateTime.now());
        learnRecordBO.setUpdateTime(LocalDateTime.now());
        learnRecordBO.setDeleteFlag(false);
    }

    @Override
    public Result<?> saveAllLearnRecord(Collection<LearnRecordBO> collection) {
        int affectedRows = learnRecordManager.saveAllLearnRecord(collection);
        if (affectedRows > 0) {
            return Result.success();
        }
        return Result.ofErrorRowsAffected();
    }

    @Override
    public Result<?> updateLearnRecord(LearnRecordBO learnRecordBO) {
        int affectedRows = learnRecordManager.updateLearnRecord(learnRecordBO);
        if (affectedRows > 0) {
            return Result.success();
        }
        return Result.ofErrorRowsAffected();
    }

    @Override
    public Result<?> deleteLearnRecord(Long learnRecordId) {
        int affectedRows = learnRecordManager.deleteLearnRecord(learnRecordId);
        if (affectedRows > 0) {
            return Result.success();
        }
        return Result.ofErrorRowsAffected();
    }

    @Override
    public LearnRecordBO getLearnRecord(Long learnRecordId) {
        return learnRecordManager.getLearnRecord(learnRecordId);
    }

    @Override
    public List<LearnRecordBO> listLearnRecordById(Collection<Long> collection) {
        return learnRecordManager.listLearnRecordById(collection);
    }

    @Override
    public List<GetLearnRecordResponse> listLearnRecord(LearnRecordQuery query) {
        List<LearnRecordBO> learnRecordBOS = learnRecordManager.listLearnRecord(query);
        learnRecordBOS = learnRecordBOS.stream().peek(l -> {
            l.setLearnDurationString(l.getLearnDuration());
            l.setLessonDurationString(l.getLessonDuration());
        }).collect(Collectors.toList());
        return LearnRecordConverter.toResponse(learnRecordBOS);
    }

    /**
     * 查找多个
     *
     * @param query 查找条件
     */
    @Override
    public List<GetLearnRecordResponse> listLearnRecord1(LearnRecordQuery query) {
        List<LearnRecordBO> learnRecordBOS = learnRecordManager.listLearnRecord(query);
        if (CollectionUtils.isEmpty(learnRecordBOS)) {
            return Collections.emptyList();
        }
        return LearnRecordConverter.toResponse(learnRecordBOS);
    }

    @Override
    public int countLearnRecord(LearnRecordQuery query) {
        Long userId = UserContextHolder.getUserId();
        UserDTO userDTO = ResultUtils.get(userClient.getUser(GetUserRequest.builder().withRole(true).userId(userId).build()));
        List<String> roleList = userDTO.getRoleList().stream().map(LongIdCodeName::getCode).collect(Collectors.toList());
        if (!roleList.contains(RoleConstant.MANAGEMENT_TRAINER)) {
            query.setLearnUserId(userId);
        }
        return learnRecordManager.countLearnRecord(query);
    }

}
